#!/usr/bin/env python
#--coding:utf-8--
import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

import paramiko

class interServer:
    def __init__(self,command,hostname,ipattr,username):
        '''

        :param command:
        :param hostname:
        :param ipattr:  ipattr=("10.0.0.20",22)
        :param username:
        '''
        self.command=command
        self.hostname=hostname
        self.ipattr=ipattr
        self.username=username
        private_key = paramiko.RSAKey.from_private_key_file("../rsa/%s_rsa"%hostname)
        transport=paramiko.Transport(ipattr)
        transport.connect(username=username, pkey=private_key)
        if command=="ssh":
            self.ssh = paramiko.SSHClient()
            self.ssh._transport=transport
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        elif command=="sftp":
            self.sftp=paramiko.SFTPClient.from_transport(transport)
    def send(self,string):
        stdin,stdout,stderr=self.ssh.exec_command(string)
        ret=stdout.read().decode()
        return ret
    def upload(self,path):
        '''
        放到对方的用户目录下同名
        :param filename:
        :return:
        '''
        filename=os.path.basename(path)
        self.sftp.put(path,'./%s'%filename)
    def listdir(self,path="."):
        self.path=path
        self.dir_list=self.sftp.listdir(path)
        return self.dir_list
    def download(self,filename):
        self.sftp.get('./%s'%filename,"../download/%s"%filename)

    def changeMode(self,command):
        self.command=command
    def close(self):
        if self.command=="ssh":
            self.ssh.close()
        elif self.command=="scp":
            self.sftp.close()


